import createDOMString from '../../utils/createDOMString';
import CMSElement from '../../utils/CMSElement';

class CmsAvatar extends CMSElement {
  props = {
    //自定义用于控制css的属性
    size: 'default',
    shape: 'circle',
    fit: 'cover',
    //懒加载相关属性
    lazyLoad: false,
    tempSrc: '',
    //原生的img标签属性
    src: '',
    alt: 'error',
    //图片加载失败回调
    error: '',
    tempError: '',
    //图片加载成功回调
    load: '',
    tempLoad: '',
    //图片预览相关属性，previewUrl为空时默认使用src路径
    previewable: false,
    previewUrl: '',
  };
  constructor() {
    super();
    this._sd = this.attachShadow({ mode: 'closed' });
    this.renderStyle();
    this.renderDom();
    const fnc = this.scrollCallBack.bind(this);
    window.addEventListener('scroll', fnc);
    this.scrollCallBack();
  }
  
  //页面滚动时的回调函数，用于懒加载功能
  scrollCallBack() {
    let ele = this._sd.querySelector('.avatar-container');
    let eleRect = ele.getBoundingClientRect();
    if (
      eleRect.top > 0 &&
      eleRect.top < window.innerHeight &&
      this.props.tempSrc != '' &&
      this.props.lazyLoad === true
    ) {
      let img = this._sd.querySelector('.avatar-container>img');
      this.props.lazyLoad = false;
      this.props.src = this.props.tempSrc;
      img.setAttribute('src', this.props.src);
      this.props.tempSrc = '';
      this.props.error = this.props.tempError;
      img.setAttribute('onerror', this.props.error);
      this.props.tempError = '';
      this.props.load = this.props.tempLoad;
      img.setAttribute('onload', this.props.load);
      this.props.tempLoad = '';
    }
  }

  //这两个render用于渲染组件默认的dom和style
  renderDom() {
    const template = document.createElement('template');
    template.innerHTML = `
      <span class="avatar-container" id="cms-avatar">
        <img src="${this.props.src}"  alt="${this.props.alt}" >
      </span>
    `;
    this._sd.appendChild(template.content.cloneNode(true));
  }
  renderStyle() {
    // 保证shadow dom中只存在一个style标签
    let style = this._sd.querySelector('style');
    if (!style) {
      style = document.createElement('style');
      this._sd.appendChild(style);
    }
    //用于css的属性值
    const styleProps = {
      size: this.props.size,
      shape: this.props.shape,
      fit: this.props.fit,
      ...this.global,
    };
    //根据不同props属性来获取不同css值
    const getSize = prop => {
      switch (prop.size) {
        case 'large':
          return '56px';
        case 'default':
          return '50px';
        case 'medium':
          return '40px';
        case 'small':
          return '24px';
        case 'auto':
          return '100%';
      }
    };
    const getShape = prop => {
      switch (prop.shape) {
        case 'circle':
          return '50%';
        case 'square':
          return '4px';
      }
    };
    style.innerHTML = createDOMString(styleProps)`
      :host {
        width: 100%;
        height: 100%;
      }
      :host > .avatar-container{
        display: inline-flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        text-align: center;
        overflow: hidden;
        color: #fff;
        background: ${styleProps.color.gray};
        width: ${getSize};
        height: ${getSize};
        font-size: 14px;
        border-radius:${getShape};
      }
      :host>.avatar-container>img{
        object-fit:${this.props.fit};
        display:block;
        height:100%;
        max-width:100%;
        border-style:none;
      }
    `;
  }

  //下面两个render用于渲染预览图片的dom和style
  renderPreviewDom() {
    const template = document.createElement('template');
    template.innerHTML = createDOMString()`
      <div class="preview">
        <img src="${this.props.previewUrl || this.props.src}">
        <button>
        <svg t="1669180518303" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7820"><path d="M780.586667 303.573333a42.538667 42.538667 0 1 0-60.16-60.16L512 451.84 303.573333 243.413333a42.538667 42.538667 0 0 0-60.16 60.16L451.84 512l-208.426667 208.426667a42.538667 42.538667 0 0 0 60.16 60.16L512 572.16l208.426667 208.426667a42.538667 42.538667 0 1 0 60.16-60.16L572.16 512l208.426667-208.426667z" fill="#959BA7" p-id="7821"></path></svg>
        </button>
      </div>
    `;
    document.body.appendChild(template.content.cloneNode(true));
    let previewDiv = document.body.querySelector('.preview');
    let previewButton = previewDiv.querySelector('button');
    const clearPreview = () => {
      document.body.removeChild(previewDiv);
    };
    previewButton.addEventListener('click', clearPreview);
  }
  renderPreviewStyle() {
    // 保证shadow dom中只存在一个style标签
    let previewDiv = document.body.querySelector('.preview');
    let previewImg = previewDiv.querySelector('img');
    let previewButton = previewDiv.querySelector('button');
    let buttonSvg = previewButton.querySelector('svg');
    Object.assign(previewDiv.style, {
      position: 'fixed',
      left: '0px',
      top: '0px',
      width: '100%',
      height: '100%',
      backgroundColor: 'rgba(0, 0, 0, 0.2)',
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
    });
    Object.assign(previewImg.style, {
      display: 'inline-block',
    });
    Object.assign(buttonSvg.style, {
      height: '100%',
    });
    Object.assign(previewButton.style, {
      position: 'absolute',
      top: '5px',
      right: '20px',
      height: '50px',
      width: '50px',
      padding: '0px',
      border: '0px solid',
      borderRadius: '50%',
      // backgroundColor: 'rgba(0, 0, 0, 0.2)',
    });
  }

  //选择要监听的属性值并进行相关操作
  static get observedAttributes() {
    return [
      'size',
      'shape',
      'src',
      'lazy-load',
      'alt',
      'fit',
      'error',
      'load',
      'previewable',
      'preview-url',
    ];
  }
  attributeChangedCallback(name, last, cur) {
    let img = this._sd.querySelector('.avatar-container>img');
    if (name === 'size') {
      const typeArr = ['large', 'default', 'medium', 'small', 'auto'];
      this.props.size = typeArr.includes(cur) ? cur : 'default';
      this.renderStyle();
    } else if (name === 'shape') {
      const typeArr = ['circle', 'square'];
      this.props.shape = typeArr.includes(cur) ? cur : 'circle';
      this.renderStyle();
    } else if (name === 'src') {
      if (this.props.lazyLoad == false) {
        this.props.src = cur;
        this.props.tempSrc = '';
        img.setAttribute('src', this.props.src);
      } else {
        this.props.tempSrc = cur;
        this.props.src = '';
      }
    } else if (name === 'lazy-load') {
      typeof cur === 'boolean'
        ? (this.props.lazyLoad = cur)
        : (this.props.lazyLoad = Boolean(cur === 'true'));
    } else if (name === 'alt') {
      this.props.alt = cur;
      img.setAttribute('alt', this.props.alt);
    } else if (name === 'fit') {
      this.props.fit = cur;
      this.renderStyle();
    } else if (name === 'error') {
      if (this.props.lazyLoad == false) {
        this.props.error = cur;
        this.props.tempError = '';
        img.setAttribute('onerror', this.props.error);
      } else {
        this.props.tempError = cur;
        this.props.error = '';
      }
    } else if (name === 'load') {
      if (this.props.lazyLoad == false) {
        this.props.load = cur;
        this.props.tempLoad = '';
        img.setAttribute('onload', this.props.load);
      } else {
        this.props.tempLoad = cur;
        this.props.load = '';
      }
    } else if (name === 'previewable') {
        typeof cur === 'boolean'
          ? (this.props.previewable = cur)
          : (this.props.previewable = Boolean(cur === 'true'));
      if (this.props.previewable === true) {
        const imgSpan = this._sd.querySelector('#cms-avatar');
        imgSpan.addEventListener('click', () => {
          this.renderPreviewDom();
          this.renderPreviewStyle();
        });
      }
    } else if (name === 'preview-url') {
      this.props.previewUrl = cur;
    }
  }
}

//创建自定义标签
customElements.define('cms-avatar', CmsAvatar);
